package edu.ccut.saturn.component.impl.sql;

import java.util.Map;

import edu.ccut.saturn.component.ISaturnDataSqlItemInfo;

public class DynamicItemInfo extends AbstractSqlItemInfo {

	public DynamicItemInfo(String prepend) {
		super(prepend);
	}

	@Override
	public String getSubSql(Map<String, Object> param) throws Exception {
		StringBuffer sqlBuffer = new StringBuffer(" ");
		boolean isPrependFlag = true;
		String firstPrependStr = null;

		for (ISaturnDataSqlItemInfo sqlItemInfo : super
				.getSaturnDataSqlItemInfos()) {

			sqlBuffer.append(sqlItemInfo.getSubSql(param));

			if (isPrependFlag) {

				if (sqlItemInfo.getSubSql(param).length() > 1) {
					firstPrependStr = sqlItemInfo.getPrepend();

					if (firstPrependStr != null) {
						isPrependFlag = false;
					}
				}
			}
		}

		if (!"".equals(sqlBuffer.toString())) {
			replaceKeyWord(sqlBuffer, firstPrependStr);
		}
		return sqlBuffer.toString();
	}

	private void replaceKeyWord(StringBuffer sqlBuffer, String firstPrependStr) {

		if (this.getPrepend() != null && !"".equals(this.getPrepend())) {

			if (firstPrependStr != null) {
				int index = sqlBuffer.indexOf(firstPrependStr);

				if (index != -1) {
					sqlBuffer.replace(index, index + firstPrependStr.length(),
							this.getPrepend());
				}
			}
		}
	}

	@Override
	public String getType() {
		return "dynamic";
	}
}
